package com.qixin.modules.eaBasic.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.entity.ActivitiConstant;
import org.jeecg.modules.activiti.mapper.ActEaTaskMapper;
import org.jeecg.modules.activiti.service.Impl.ActBusinessServiceImpl;
import org.jeecg.modules.activiti.service.Impl.ActZprocessServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:wly
 * @Date:2021/10/26
 * @Describtion: 工作流工具类
 */
@Service
public class WorkFlowUtil {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ActBusinessServiceImpl actBusinessService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ActZprocessServiceImpl actZprocessService;
    @Autowired
    ISysBaseAPI sysBaseAPI;
    @Autowired
    ActEaTaskMapper actEaTaskMapper;

    public void deleteWorkFlowById(String id,String procInstId){
        String comment = "删除";
        // 删除流程实例
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        if(pi != null){
            taskService.addComment(id, procInstId, comment);

            ActBusiness actBusiness = actBusinessService.getById(pi.getBusinessKey());
            actBusiness.setStatus(ActivitiConstant.STATUS_FINISH);
            actBusiness.setResult(ActivitiConstant.RESULT_FAIL);
            actBusinessService.updateById(actBusiness);
            // 异步发消息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            actZprocessService.sendMessage(actBusiness.getId(),sysUser,sysBaseAPI.getUserById(actBusiness.getUserId()),ActivitiConstant.MESSAGE_BACK_CONTENT,
                    String.format("您的 【%s】 申请已被驳回！",actBusiness.getTitle()),true, false, false);
            // 记录实际审批人员
            actBusinessService.insertHI_IDENTITYLINK(IdUtil.simpleUUID(),
                    ActivitiConstant.EXECUTOR_TYPE_b, sysUser.getUsername(), id, procInstId);
            //将待办任务删除
            actEaTaskMapper.deleteActRuIdentity(id);

            //删除待办任务(act_ru_task)字段:id_(待办任务id)
            actEaTaskMapper.deleteRuTask(id);
        }
    };
}
